{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction\n",
    "The maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum.\n",
    "\n",
    "Example, For the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6.\n",
    "\n",
    "# Approach 1\n",
    "Initialize:\n",
    "\n",
    "    max_so_far = 0\n",
    "    max_ending_here = 0\n",
    "\n",
    "Loop for each element of the array\n",
    "\n",
    "(a) max_ending_here = max_ending_here + a[i]  \n",
    "(b) if(max_ending_here < 0)\n",
    "    \n",
    "    max_ending_here = 0\n",
    "(c) if(max_so_far < max_ending_here)  \n",
    "    \n",
    "    max_so_far = max_ending_here\n",
    "\n",
    "return max_so_far"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "data = [-2, 1, -3, 4, -1, 2, 1, -5, 4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def max_contiguous_subarray(data):\n",
    "    ans = data[0]\n",
    "    max_ending_here = data[0]\n",
    "    for x in data[1:]:\n",
    "        max_ending_here = max(x, max_ending_here + x)\n",
    "        ans = max(ans, max_ending_here)\n",
    "    return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n"
     ]
    }
   ],
   "source": [
    "print max_contiguous_subarray(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# References\n",
    "- https://en.wikipedia.org/wiki/Maximum_subarray_problem\n",
    "- http://www.geeksforgeeks.org/largest-sum-contiguous-subarray/\n",
    "- http://codeforces.com/blog/entry/13713\n",
    "- http://practice.geeksforgeeks.org/problems/kadanes-algorithm/0"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
